package base.httpclient.demo01;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class GetRequest {

    public static void main(String[] args) {
        String baidu = "https://www.baidu.com";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 这是请求头
            HttpGet httpGet = new HttpGet(baidu);
//            httpGet.addHeader("","");//可重复添加请求头
            httpGet.setHeader("content-type","text/html;charset=utf-8");//覆盖添加同名请求头
            // 解决httpClient被认为不是真人行为
            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
            // 解决防盗链问题
            httpGet.setHeader("Referer","https://www.baidu.com/");


            // execute()方法执行httpGet请求，并将结果作为execute()方法的第二个入参
            String responseBody = httpClient.execute(httpGet, httpResponse -> {
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status < HttpStatus.SC_OK || status >= HttpStatus.SC_MULTIPLE_CHOICES) {
                    // ... handle unsuccessful request
                    System.out.println("请求出错了，状态码："+status);
                }
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity, StandardCharsets.UTF_8) : null;
            });
            // ... do something with response
            System.out.println(responseBody);
        } catch (IOException e) {
            // ... handle IO exception
        }
    }

}
